#include <queue>

using namespace std;

class Solution {
public:
    vector<int> findDiagonalOrder(vector<vector<int>>& nums) {
        queue<pair<int, int>> queue;
        vector<int> ans;
        queue.push({0, 0});
        while (!queue.empty()) {
            for (int i = 0, len = queue.size(); i < len; i++) {
                pair<int, int> front = queue.front();
                if (front.first + 1 < nums.size() && front.second < nums[front.first + 1].size() && queue.back() != pair<int, int>{front.first + 1, front.second}) {
                    queue.push({front.first + 1, front.second});
                }
                if (front.second + 1 < nums[front.first].size()) {
                    queue.push({front.first, front.second + 1});
                }
                queue.pop();
                ans.push_back(nums[front.first][front.second]);
            }
        }
        return ans;
    }
};